package com.shelpe.services.scheduler.item.adgroup;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.NonTransientResourceException;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import com.shelpe.services.scheduler.po.Adgroups;
import com.shelpe.services.scheduler.repository.AdgroupsRepository;

@Component("singleUserAdgroupReader")
@Scope("step")	
public class SingleUserAdgroupReader implements ItemReader<Adgroups>{

	private static final Logger logger = LoggerFactory.getLogger(SingleUserAdgroupReader.class);
	
	@Autowired
	private AdgroupsRepository adRep;
    
    private final Long pageNo;
    
    private final Long pageSize;
    
    private final Long userId;
    
    private int current;
    
    private List<Adgroups> onePage;
    	
	
	@Autowired
    public SingleUserAdgroupReader(@Value("#{jobParameters['pageNo']}")final Long pageNo, @Value("#{jobParameters['pageSize']}")final Long pageSize,
    		@Value("#{jobParameters['userId']}")final Long userId){
        
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.userId = userId;
        this.current = 0;
    }
	
	
	@Override
	public Adgroups read() throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
		// TODO Auto-generated method stub

		if(onePage == null || onePage.size() == 0){

			if(pageNo >= 0 && pageSize > 0){
				
				Pageable pager = new PageRequest(pageNo.intValue(), pageSize.intValue());
				Page<Adgroups> list = adRep.findByUserId(userId, pager);

				onePage = list.getContent();
				logger.info("SingleUserAdgroupReader pageNo {}, pageSize {}, userId {}", pageNo, pageSize, userId);
			}
		}
		
		if(onePage != null && current < onePage.size()){
			int beginIndex = current;
			current++;
			return onePage.get(beginIndex);			
		}

		return null;
	}

}
